package com.tenglong.teacher;


import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.cuotibao.zhuoxiao.basics.BaseApplication;
import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.utils.IpUtils;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.api.UIKitOptions;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.util.NIMUtil;
import com.tenglong.teacher.data.resultInfo.ClientUserInfo;
import com.tenglong.teacher.data.resultInfo.DataState;
import com.tenglong.teacher.ui.nimchat.DemoCache;
import com.tenglong.teacher.ui.nimchat.NIMInitManager;
import com.tenglong.teacher.ui.nimchat.NimSDKOptionConfig;
import com.tenglong.teacher.ui.notiUtil.NotificationModule;

import java.io.Serializable;
import java.util.List;


/**
 * Created by Kevin on 2017/12/22.
 */

public class MyApplication extends BaseApplication {

    private static NotificationModule mNotificationModel;

    public void onCreate() {
        super.onCreate();
        // 以下逻辑只c在主进程初始化时执行
        DemoCache.setContext(this);
        initNIMClient();
        if (NIMUtil.isMainProcess(this)) {
            // 初始化UIKit模块
            initUIKit();
            // 初始化消息提醒
            // NIMClient.toggleNotification(UserPreferences.getNotificationToggle());
            //关闭撤回消息提醒
            NIMClient.toggleRevokeMessageNotification(false);
            NIMClient.toggleNotification(false);
            // 云信sdk相关业务初始化
            NIMInitManager.getInstance().init(true);
            //通知
            mNotificationModel = new NotificationModule(this);
        }
    }

    private void initNIMClient() {
        NIMClient.init(this, loginInfo(), NimSDKOptionConfig.getSDKOptions(this));
    }

    private LoginInfo loginInfo() {
        return DataState.getInstance().getWYLoginInfo();
    }

    public static void registerNotificationObserver() {
        mNotificationModel.registerNotificationObserver();
    }

    public static void unRegisterNotificationObserver() {
        mNotificationModel.unRegisterNotificationObserver();
    }

    private UIKitOptions buildUIKitOptions() {
        UIKitOptions options = new UIKitOptions();
        // 设置app图片/音频/日志等缓存目录
        options.appCacheDir = NimSDKOptionConfig.getAppCacheDir(this) + "/app";
        return options;
    }

    private void initUIKit() {
        // 初始化
        NimUIKit.init(this, buildUIKitOptions());
        // 设置地理位置提供者。如果需要发送地理位置消息，该参数必须提供。如果不需要，可以忽略。
        //NimUIKit.setLocationProvider(new NimDemoLocationProvider());
        // 通讯录列表定制初始化
        //  ContactHelper.init();
        // 添加自定义推送文案以及选项，请开发者在各端（Android、IOS、PC、Web）消息发送时保持一致，以免出现通知不一致的情况
        //  NimUIKit.setCustomPushContentProvider(new DemoPushContentProvider());
        // NimUIKit.setOnlineStateContentProvider(new DemoOnlineStateContentProvider());
    }


    @Override
    protected void activityDataSave(Activity activity, Bundle outState) {
        if (outState != null) {
            outState.putInt(GlobalConstant.KEY_ORGANIZATION_INDEX, DataState.getInstance().getOrganizationIndex());
            outState.putSerializable(GlobalConstant.KEY_LOGIN_RESULT_INFO_LIST, (Serializable) DataState.getInstance().getUserInfos());
            LoginInfo wyLoginInfo = DataState.getInstance().getWYLoginInfo();
            if (wyLoginInfo != null) {
                outState.putSerializable(GlobalConstant.KEY_IM_LOGIN_INFO, wyLoginInfo);
            }
            String tempImtoken = DataState.getInstance().getTempImtoken();
            if (!TextUtils.isEmpty(tempImtoken)) {
                outState.putString(GlobalConstant.KEY_TEMP_IM_TOKEN_INFO, tempImtoken);
            }
            outState.putBoolean(GlobalConstant.KEY_IS_LOGIN, DataState.getInstance().isLoginState());
            outState.putBoolean(GlobalConstant.KEY_CORRELATION_ANSWER_IS_CLASS_NUMBER_CHANGE, DataState.getInstance().isCorrelationAnswerIsClassNumChange());
        }
    }

    @Override
    protected void activityDataReset(Activity activity, Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            DataState datastate = DataState.getInstance();
            if (savedInstanceState.containsKey(GlobalConstant.KEY_ORGANIZATION_INDEX)) {
                datastate.setOrganizationIndex(savedInstanceState.getInt(GlobalConstant.KEY_ORGANIZATION_INDEX));
            }
            if (savedInstanceState.containsKey(GlobalConstant.KEY_LOGIN_RESULT_INFO_LIST)) {
                List<ClientUserInfo> mUserInfo = (List<ClientUserInfo>) savedInstanceState.getSerializable(GlobalConstant.KEY_LOGIN_RESULT_INFO_LIST);
                if (mUserInfo != null) {
                    datastate.setUserInfos(mUserInfo);
                }
            }
            if (savedInstanceState.containsKey(GlobalConstant.KEY_IM_LOGIN_INFO)) {
                LoginInfo loginInfo = (LoginInfo) savedInstanceState.getSerializable(GlobalConstant.KEY_IM_LOGIN_INFO);
                if (loginInfo != null) {
                    datastate.setWYLoginInfo(loginInfo);
                }
            }
            if (savedInstanceState.containsKey(GlobalConstant.KEY_TEMP_IM_TOKEN_INFO)) {
                String tempImtoken = savedInstanceState.getString(GlobalConstant.KEY_TEMP_IM_TOKEN_INFO);
                if (tempImtoken != null) {
                    datastate.setTempImtoken(tempImtoken);
                }
            }
            if (savedInstanceState.containsKey(GlobalConstant.KEY_IS_LOGIN)) {
                boolean loginState = savedInstanceState.getBoolean(GlobalConstant.KEY_IS_LOGIN, false);
                datastate.setLoginState(loginState);
            }
            if (savedInstanceState.containsKey(GlobalConstant.KEY_DEBUG_INDEX)) {
                int index = savedInstanceState.getInt(GlobalConstant.KEY_DEBUG_INDEX, 0);
                IpUtils.IpIndex = index;
            }
            if (savedInstanceState.containsKey(GlobalConstant.KEY_CORRELATION_ANSWER_IS_CLASS_NUMBER_CHANGE)) {
                boolean isChange = savedInstanceState.getBoolean(GlobalConstant.KEY_CORRELATION_ANSWER_IS_CLASS_NUMBER_CHANGE, false);
                datastate.setCorrelationAnswerIsClassNumChange(isChange);
            }
        }
    }

    @Override
    public String getOrganizationUrl() {
        DataState dataState = DataState.getInstance();
        String url;
        if (dataState.isLoginState()){
            url = dataState.getUserInfo().getUrl();
            if (TextUtils.isEmpty(url)){
                url =  IpUtils.Ips[IpUtils.IpIndex];
            }
        } else {
            url = IpUtils.Ips[IpUtils.IpIndex];
        }
        return url == null ? "" : url;
    }

    @Override
    public boolean getLoginState() {
        return DataState.getInstance().isLoginState();
    }
}
